import { baseRequestClient, requestClient } from '#/api/request';

export namespace AuthApi {
  /** 登录接口参数 */
  export interface LoginParams {
    username: string;
    password: string;
  }

  /** 登录接口返回值 */
  export interface LoginResult {
    access_token: string;
    refresh_token: string;
  }
  /** 注册接口参数 */
  export interface RegisterParams {
    username: string;
    password: string;
    email: string;
    institution?: string;
  }
  export interface RegisterResult {
    message: string;
  }
  export interface RefreshTokenResult {
    data: { data: { access_token: string; refresh_token: string } };
    status: string;
  }
}

/**
 * 登录
 */
// 固定参数
const fixedParams = {
  client_id: 'scene_container',
  client_secret: 'opengms@uo~U%VGPm38S5HV',
  grant_type: 'password',
};

async function loginApi(data: AuthApi.LoginParams) {
  return requestClient.post<AuthApi.LoginResult>(
    '/dsc-systemMS/dsc-user/login',
    { ...fixedParams, ...data },
  );
}

/**
 * 注册
 */
async function registerApi(data: AuthApi.RegisterParams) {
  return requestClient.post<AuthApi.RegisterResult>(
    '/dsc-systemMS/dsc-user/register',
    { ...data },
  );
}

/**
 * 通过激活码激活用户
 */
async function activeUserApi(code: string) {
  return requestClient.get(`/dsc-systemMS/dsc-user/active/${code}`);
}

/**
 * 刷新accessToken`
 */
async function refreshTokenApi(refreshToken: null | string) {
  const formData = new FormData();
  formData.append('grant_type', 'refresh_token');
  formData.append('refresh_token', refreshToken as string);
  formData.append('client_id', 'scene_container');
  formData.append('client_secret', 'opengms@uo~U%VGPm38S5HV');
  return baseRequestClient.post<AuthApi.RefreshTokenResult>(
    '/dsc-auth-central/oauth/token',
    formData,
    {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    },
  );
}

/**
 * 退出登录
 */
async function logoutApi() {
  return requestClient.get('/dsc-systemMS/dsc-user/logout');
}

/**
 * 获取用户权限码
 */
async function getAccessCodesApi() {
  // return requestClient.get<string[]>('/auth/codes');
  return [];
}

export default {
  loginApi,
  registerApi,
  activeUserApi,
  refreshTokenApi,
  logoutApi,
  getAccessCodesApi,
};
